package kr.pe.johnkim.sendme.activity;

import java.util.ArrayList;
import java.util.List;

import kr.pe.johnkim.sendme.provider.SendMeCertification;
import kr.pe.johnkim.sendme.provider.SendMeInstall;
import kr.pe.johnkim.sendme.provider.SendMeLog;
import kr.pe.johnkim.sendme.provider.SendMeMember;
import kr.pe.johnkim.sendme.rest.SendMeCertificationRest;
import kr.pe.johnkim.sendme.rest.SendMeInstallRest;
import kr.pe.johnkim.sendme.rest.SendMeLogRest;
import kr.pe.johnkim.sendme.rest.SendMeMemberRest;
import kr.pe.johnkim.sendme.util.GMailSender;
import kr.pe.johnkim.sendme.util.SendMeActivityManager;
import kr.pe.johnkim.sendme.util.SendMeCommon;
import kr.pe.johnkim.sendme.util.SendMeConstant;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.ContactsContract;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.Toast;

public class SendMeSubSettingsRequestToAdminActivity extends Activity {

	public static String TAG = SendMeSubSettingsRequestToAdminActivity.class.getSimpleName();
	
	
	// 액티비티 매니저를 가져 온다.
	private SendMeActivityManager sendMeActivityManager = SendMeActivityManager.getInstance();
	
	ImageButton imageButtonTopBack;
	ImageButton imageButtonTopMainMenu;
	
	EditText requestToAdminSubjectTxt;
	EditText requestToAdminContentTxt;

	String GMAIL_SENDER_ID = SendMeConstant.GMAIL_SENDER_ID;
	String GMAIL_SENDER_PWD = SendMeConstant.GMAIL_SENDER_PWD;
	String GMAIL_RECEIVER_ID = SendMeConstant.GMAIL_RECEIVER_ID;
	
	// 사용자 휴대 전화번호.
	private String PHONE_NUMBER = "";
	
	String requestToAdminSubjectTxtStr;
	String requestToAdminContentTxtStr;
	
	Button requestToAdminConfirmBtn;
	
	// 메일 발송
	ProgressDialog dialog;
	GMailSender sender;
	
//	// 요청 메일을 발송한다
//	private static final int THREAD_SEND_MAIL = 102;

	
	// 로그를 남긴다
	private static final int THREAD_REGISTER_LOG = 100;
	
	// 메일 전송에 성공했다는 toast 를 띄운다.
	private static final int THREAD_SUCCESS_SEND_MAIL = 103;
	
	// 메일 전송에 실패했다는 toast 를 띄운다.
	private static final int THREAD_FAIL_SEND_MAIL = 104;
	
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		// 커스텀 타이블 바를 설정 한다.
		Window window = getWindow();
		window.requestFeature(Window.FEATURE_CUSTOM_TITLE);
				
		setContentView(R.layout.activity_send_me_sub_settings_request_to_admin);
		
		window.setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title_bar_03);
		
		// 액티비티 매니저에 담는다.
		sendMeActivityManager.addActivity(this);
		
		// 설정파일을 가져 온다.
		this.confirmNotification();
		
		// 뒤로 가기 화살표 버튼을 설정 한다.
				imageButtonTopBack = (ImageButton)findViewById(R.id.imageButtonTopBack);
				imageButtonTopBack.setOnClickListener(new View.OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub

						Intent intent = new Intent(returnThis(), SendMeSettingsActivity.class);
						startActivity(intent);
						
						// 화면을 닫는다.
						sendMeActivityManager.removeActivity(SendMeSubSettingsRequestToAdminActivity.this);
						finish();
					}
				});

				// 타이틀바의 메인 메뉴 버튼을 설정 한다.
				imageButtonTopMainMenu = (ImageButton)findViewById(R.id.imageButtonTopMainMenu);
				imageButtonTopMainMenu.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						Log.i(TAG, "pressed top main menu.");

						// 메인 메뉴 화면을 출력 한다.
						Intent i = new Intent(SendMeSubSettingsRequestToAdminActivity.this, SendMeMainMenuActivity.class);
						startActivity(i);
						
						// 화면을 닫는다.
						sendMeActivityManager.removeActivity(SendMeSubSettingsRequestToAdminActivity.this);
						finish();
					}
				});
				
				
		// 메일 센더 초기화
		sender = new GMailSender(GMAIL_SENDER_ID, GMAIL_SENDER_PWD);

		// 제목 입력창
		requestToAdminSubjectTxt = (EditText)findViewById(R.id.request_to_admin_subject_txt);
		requestToAdminSubjectTxt.requestFocus();
		// 내용 입력창
		requestToAdminContentTxt = (EditText)findViewById(R.id.request_to_admin_content_txt);

		// 확인 버튼
		requestToAdminConfirmBtn = (Button)findViewById(R.id.request_to_admin_confirm_btn);
		requestToAdminConfirmBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
//				// TODO Auto-generated method stub
				requestToAdminSubjectTxtStr = requestToAdminSubjectTxt.getText()+"";
				requestToAdminContentTxtStr = requestToAdminContentTxt.getText()+"";
				if(requestToAdminSubjectTxtStr.length()>0 && requestToAdminContentTxtStr.length()>0){
					sendMailThread();
				}
			}
			
		});
		
		// 로깅.
		mHandler.sendMessage(mHandler.obtainMessage(THREAD_REGISTER_LOG));
		
		
	}

//	@Override
//	public boolean onCreateOptionsMenu(Menu menu) {
//		// Inflate the menu; this adds items to the action bar if it is present.
//		getMenuInflater().inflate(R.menu.send_me_certification, menu);
//		return true;
//	}
	
	/**
	 * Handler 를 정의 한다.
	 * 모든 Thread 를 등록해 놓고 호출 한다.
	 */
	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch(msg.what) {
			
			// 로그를 남긴다
			case THREAD_REGISTER_LOG : 
				threadRegisterLog();
				break;
//				// 메일 보내기
//			case THREAD_SEND_MAIL : 
//				break;
				// 메일 전송에 성공했다는 toast 를 띄운다.
			case THREAD_SUCCESS_SEND_MAIL : 
				showToastSuccessSendMail();			
				break;
				// 메일 전송에 실패했다는 toast 를 띄운다.
			case THREAD_FAIL_SEND_MAIL : 
				showToastFailSendMail();
				break;
			}
		}
	};

	public Context returnThis(){
		return this;
	}
	
	//////////////////////////////////////////////////////////////////////////////////////////////////////////
	// mail 보내기
	
	
	public void sendMailThread() {

		dialog = new ProgressDialog(returnThis());
		dialog.setTitle("Wait...");
		dialog.setMessage("의견을 보내는 중입니다.");
		dialog.setIndeterminate(true);
//		dialog.setCancelable(true);
		dialog.show();
		new Thread(new Runnable() {

			public void run() {
				// TODO Auto-generated method stub
				try {
					sender.sendMail(requestToAdminSubjectTxtStr, // subject.getText().toString(),
							requestToAdminContentTxtStr, // body.getText().toString(),
							GMAIL_SENDER_ID, // from.getText().toString(),
							GMAIL_RECEIVER_ID // to.getText().toString()
					);
					mHandler.sendMessage(mHandler.obtainMessage(THREAD_SUCCESS_SEND_MAIL));
					finishActivity();
				} catch (Exception e) {
					Log.e("SendMail", e.getMessage(), e);
					mHandler.sendMessage(mHandler.obtainMessage(THREAD_FAIL_SEND_MAIL));
//					Toast.makeText(MainActivity.this, "요청이 실패하였습니다.", Toast.LENGTH_SHORT).show();		

				}
				dialog.dismiss();
			}

			private void sleep(int i) {
				// TODO Auto-generated method stub

			}

		}).start();
	}
	
	
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////	
	// 서버 통신
	
	/**
	 * 로그를 남긴다	 
	 */
	public void threadRegisterLog() {
		Thread thread = new Thread(new Runnable() {
			public void run() {
				
				SendMeCommon sendMeCommon = new SendMeCommon();
				String nowTime = sendMeCommon.getCurrentDate();
				
				SendMeLog sendMeLog = new SendMeLog();
				sendMeLog.setPhoneNumber(PHONE_NUMBER);
				sendMeLog.setViewName(TAG);
				sendMeLog.setRegisterDate(nowTime);
				
				SendMeLogRest sendMeLogRest = new SendMeLogRest();
				
				sendMeLogRest.registerLog(sendMeLog);
			}
		});
		thread.start();
	}
	


/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	// 사용자 알림
	
	/**
	 * 메일 전송에 성공했다는 toast 를 띄운다.
	 */			
	public void showToastSuccessSendMail() {			
		CharSequence text = "메일이 발송되었습니다.";
		Toast toast = Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT);
		toast.setGravity(Gravity.CENTER_VERTICAL|Gravity.CENTER_HORIZONTAL, 0, 0);
		toast.show();
	}
	
	/**
	 * 메일 전송에 실패했다는 toast 를 띄운다.
	 */
	public void showToastFailSendMail() {
		CharSequence text = "요청이 실패하였습니다.";
		Toast toast = Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT);
		toast.setGravity(Gravity.CENTER_VERTICAL|Gravity.CENTER_HORIZONTAL, 0, 0);
		toast.show();
	}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	/**
	 * SharedPreference 정보를 확인 한다.
	 */
	public void confirmNotification() {
		SharedPreferences mSharedPreference = getSharedPreferences(SendMeConstant.SENDME_PREFERENCE, Activity.MODE_PRIVATE);

		PHONE_NUMBER = mSharedPreference.getString("phone_number", "");
	}

	
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	// 닫기 관련
	
	
	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		Intent intent = new Intent(returnThis(), SendMeSettingsActivity.class);
		startActivity(intent);
		
		// 화면을 닫는다.
		sendMeActivityManager.removeActivity(SendMeSubSettingsRequestToAdminActivity.this);
		finish();
	}
	
	/*
	 * 종료한다
	 */
	public void finishActivity(){
		sendMeActivityManager.removeActivity(SendMeSubSettingsRequestToAdminActivity.this);
		finish();
	}

}
